package com.baosight.sczx.common.zm.upload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.baosight.iplat4j.core.resource.I18nMessages;
import com.baosight.sczx.common.zm.cInterface.cd.Documents;

/**
 * 
 * <p>Title: ApacheFileUploadServlet.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 严洪浩
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-25 上午07:51:49  严洪浩  Create
 *</pre>
 */
@SuppressWarnings("serial")
public class ApacheFileUploadServlet extends HttpServlet {
 
	public ApacheFileUploadServlet() {
		super();
	}
 
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    	//设置返回的信息
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        String str = "error";
        /**  
         * form中的enctype必须是multipart/...  
         * 组件提供方法检测form表单的enctype属性  
         * 在isMultipartContent方法中同时检测了是否是post提交  
         * 如果不是post提交则返回false  
         */  
        if(ServletFileUpload.isMultipartContent(request)) {          	
        	request.setCharacterEncoding("utf-8");   
            DiskFileItemFactory factory = new DiskFileItemFactory();   
            /**  
             * 临时文件存储路径要真实存在  
             */  
			File tmpDir = new File("c:/tmp");
			if(!tmpDir.exists())
			{
				tmpDir.mkdir();						
			}
            factory.setRepository(tmpDir);   
            //内存最大占用   
            factory.setSizeThreshold(1024000);   
            ServletFileUpload sfu = new ServletFileUpload(factory);   
            //单个文件最大值byte   
            sfu.setFileSizeMax(102400000);   
            //所有上传文件的总和最大值byte   
            sfu.setSizeMax(204800000);   
            List items = null;   
            try {   
                items = sfu.parseRequest(request);  
                
                Iterator iter = items==null?null:items.iterator();
                Map map = new HashMap();
                while(iter != null && iter.hasNext()) {   
                    FileItem item = (FileItem)iter.next();   
                    //简单的表单域   
                    if(item.isFormField()) {   
                        System.out.print("form field:");   
                        System.out.print(item.getFieldName() + "  ");   
                        System.out.print(item.getString());   
                    }    
                    //文件域   
                    else if(!item.isFormField()) {   
//                        System.out.println("client name:" + item.getName());   
//                        String fileName = item.getName();   
//                        BufferedInputStream in = new BufferedInputStream(item.getInputStream());   
//                        //文件存储在工程的upload目录下,这个目录也得存在   
//                        BufferedOutputStream out = new BufferedOutputStream(   
//                                new FileOutputStream(new File("c:/temp/" + fileName)));   
//                        Streams.copy(in, out, true);   
    					File fullFile = new File(item.getName());
    					
    					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmss");
    					String saveName = sdf.format(new Date()) + fullFile.getName();
    					String keepDir = I18nMessages.getText("znh.updownload.uploadfilekeepeddir");
    					
    					File dir = new File(keepDir);
    					if(!dir.exists())
    					{
    						dir.mkdir();						
    					}
    					
    					File newFile = new File(keepDir + saveName);
    					try {
    						item.write(newFile);
    						String fdKeyId = Documents.insertFile(saveName, fullFile.getName(), convert(newFile.length()));
    						if(fdKeyId != null)
    						{
    							map.put(saveName, fdKeyId);
    						}
    						else
    						{
    							newFile.delete();
    						}
    					} catch (Exception e) {
    						response.sendError(0, "无法写入文件！"+e.getMessage());
    						e.printStackTrace();
    						return;
    					}
                    }   
                } 
                
                str = "";
                for(Object obj : map.keySet())
                {
                	str += obj + "=" + map.get(obj) + "&";
                }
                
                writer.print(java.net.URLEncoder.encode(str.substring(0, str.length()-1),"utf-8"));
                writer.flush();
                writer.close();
                
            } catch (SizeLimitExceededException e) {                     
                writer.print(java.net.URLEncoder.encode(str+":超过服务器上设置的上传大小，"+e.getMessage(),"utf-8"));
                writer.flush();
                writer.close();
                System.out.println("size limit exception!"); 
            } catch(Exception e) {   
                //e.printStackTrace(); 
                writer.print(java.net.URLEncoder.encode(str+":上传文件失败，"+e.getMessage(),"utf-8"));
                writer.flush();
                writer.close();
            	System.out.println(e.getMessage());
            }   
                          
        } else {   
            System.out.println("enctype error!");  
            writer.print(java.net.URLEncoder.encode(str+":上传文件失败，enctype error!","utf-8"));
            writer.flush();
            writer.close();
        	return;
        }   
    }  
	
	
	public String convert(long value)
	{
        String size = "0 KB";

        long byteCount = value;
        DecimalFormat df = new DecimalFormat("##.##");
        if (byteCount >= 1073741824)
            size = df.format((double)byteCount / 1073741824) + " GB";
        else if (byteCount >= 1048576)
            size = df.format((double)byteCount / 1048576) + " MB";
        else if (byteCount >= 1024)
            size = df.format((double)byteCount / 1024) + " KB";
        else if (byteCount > 0 && byteCount < 1024)
            size = "1 KB";    //Bytes are unimportant ;)            


        return size;
	}
}  

			
			
			
//			DiskFileItemFactory factory = new DiskFileItemFactory();
//			factory.setRepository(new File("c:/tmp/"));
//			ServletFileUpload upload = new ServletFileUpload(factory);
//			//upload.setHeaderEncoding("gbk");
//			upload.setSizeMax(2000000);
//			List items = new ArrayList();
//			try {
//				items = upload.parseRequest(request);
//			} catch (FileUploadException e1) {
//				System.out.println("文件上传发生错误" + e1.getMessage());
//    }
//			Iterator it = items.iterator();
//			while(it.hasNext()){
//				FileItem fileItem = (FileItem) it.next();
//				if(fileItem.isFormField()){      
//					System.out.println(fileItem.getFieldName() + "   " + fileItem.getName() + "   " + new String(fileItem.getString().getBytes("iso8859-1"), "gbk"));
//				}else{
//					System.out.println(fileItem.getFieldName() + "   " + 
//							fileItem.getName() + "   " + 
//							fileItem.isInMemory() + "    " + 
//							fileItem.getContentType() + "   " + 
//							fileItem.getSize());
//     
//					if(fileItem.getName()!=null && fileItem.getSize()!=0){
//						File fullFile = new File(fileItem.getName());
//						File newFile = new File("c:/temp/" + fullFile.getName());
//						try {
//							fileItem.write(newFile);
//						} catch (Exception e) {
//							e.printStackTrace();
//						}
//					}else{
//						System.out.println("文件没有选择 或 文件内容为空");
//					}
//				}
//     
//			}
//		}
//	}
//}
